# 导入必要的库和模块
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import pickle
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import os
os.environ["LOKY_MAX_CPU_COUNT"] = "12"  # 根据你的 CPU 核心数调整
# 加载数字数据集
digits = datasets.load_digits()
X = digits.data
y = digits.target

# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_accuracy = 0
best_k = 0
best_knn_model = None
k_values = []
accuracies = []
# 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
for k in range(1, 41):
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)
    k_values.append(k)
    accuracies.append(accuracy)
    if accuracy > best_accuracy:
        best_accuracy = accuracy
        best_k = k
        best_knn_model = knn

# 将最佳KNN模型保存到二进制文件
with open('best_knn_model.pkl', 'wb') as f:
    pickle.dump(best_knn_model, f)

# 打印最佳准确率和相应的k值
print("Best Accuracy:", best_accuracy)
print("Best K value:", best_k)
#生成pdf
plt.figure(figsize=(10, 6))
plt.plot(k_values, accuracies, marker='o', label='Accuracy', color='blue')
plt.axvline(x=best_k, color='red', linestyle='--', label='Best K Value')
plt.scatter(best_k, best_accuracy, color='red')  # 标记最佳准确率点
plt.text(best_k, best_accuracy, f'  K={best_k}\n  Acc={best_accuracy:.2f}', fontsize=10, verticalalignment='bottom', color='red')

# 添加标题和标签
plt.title('KNN Classifier Accuracy for Different K Values')
plt.xlabel('K Value')
plt.ylabel('Accuracy')
plt.xticks(range(1, 41, 5))  # 从 1 到 40，步长为 5
plt.ylim((0.96, 1))
plt.legend()
plt.grid()

# 保存图表到PDF文件
pdf_filename = 'knn_accuracy_plot.pdf'
with PdfPages(pdf_filename) as pdf:
    pdf.savefig()
    plt.close()

print(f"Plot saved to {pdf_filename}")